package com.supreme.nettyapp.generalclient.socketclient.service;

import com.supreme.nettyapp.generalclient.service.NettyChannelService;
import com.supreme.nettyapp.generalclient.service.NettyClientService;
import com.supreme.nettyapp.generalclient.socketclient.handler2.SocketClientInitializer;
import com.supreme.nettyapp.generalclient.socketclient.props.SocketClientProps;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SocketClientService implements NettyClientService, NettyChannelService {

    @Resource
    private SocketClientProps socketClientProps;

    private Channel clientChannel;

    @Override
    public Channel getChannel() {
        return clientChannel;
    }

    @Override
    public void writeAndFlush(Object msg) {
        clientChannel.writeAndFlush(msg);
    }

    @Async(value = "nettyTask")
    @Override
    public void startNettyClient() {
        EventLoopGroup group = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(SocketClientInitializer.INSTANCE);

            String serverHost = socketClientProps.getServerHost();
            Integer serverPort = socketClientProps.getServerPort();
            ChannelFuture channelFuture = bootstrap.connect(serverHost, serverPort).sync();
            clientChannel = channelFuture.channel();
            clientChannel.closeFuture().sync();
        } catch (Exception e) {
            System.out.println("start exception = " + e.getMessage());
        } finally {
            group.shutdownGracefully();
        }
    }

    @Override
    public void startNettyClient(String host, int port) {

    }

    @Override
    public void destroyNettyClient() {

    }
}
